<template>
  <div class="container">
    <div v-show="user.role === 'admin'" class="library">
      <div class="partial-title">
        图书馆配置:
        <div class="custom-btn" @click="libraryFormShow = true">修改</div>
      </div>
      <el-descriptions
        :column="3"
        direction="vertical"
        border
        class="description"
      >
        <el-descriptions-item label="开馆时间">{{
          library.beginTime
        }}</el-descriptions-item>
        <el-descriptions-item label="闭馆时间">{{
          library.endTime
        }}</el-descriptions-item>
        <el-descriptions-item label="图书租金"
          >{{ library.perDayPay }}/每天</el-descriptions-item
        >
      </el-descriptions>
    </div>
    <div>
      <div class="partial-title">
        用户信息:
        <div
          class="custom-btn"
          style="width: 6vw; right: 8vw !important"
          @click="passwordFormShow = true"
        >
          密码修改
        </div>
        <div class="custom-btn" style="width: 6vw" @click="handleEditor()">
          个人信息修改
        </div>
      </div>
      <el-descriptions :column="2" border class="description">
        <el-descriptions-item label="ID">{{ user.id }}</el-descriptions-item>
        <el-descriptions-item label="头像">
          <img
            class="head"
            :src="
              user.headImgUrl ? baseImgurl + user.headImgUrl : defaultHeadImg
            "
          />
        </el-descriptions-item>
        <el-descriptions-item label="昵称">{{
          user.nickName
        }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{
          user.idCard
        }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{
          user.mobile
        }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{
          user.email
        }}</el-descriptions-item>

        <el-descriptions-item label="居住地">{{
          user.location
        }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <el-dialog title="密码修改" :visible.sync="passwordFormShow">
      <el-form
        :model="passwordForm"
        :rules="rules"
        ref="passwordForm"
        label-position="left"
      >
        <el-form-item
          label="老密码"
          :label-width="defaultLabelWidth"
          prop="oldPassword"
          maxlength="20"
        >
          <el-input
            v-model="passwordForm.oldPassword"
            autocomplete="off"
            style="width: 15vw"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="新密码"
          :label-width="defaultLabelWidth"
          prop="newPassword"
          maxlength="20"
        >
          <el-input
            v-model="passwordForm.newPassword"
            autocomplete="off"
            type="password"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle('passwordForm')">取 消</el-button>
        <el-button type="primary" @click="confirmChange()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="个人信息修改" :visible.sync="editorformShow">
      <el-form
        :model="editorform"
        :rules="rules"
        ref="editorform"
        label-position="left"
      >
        <el-form-item label="头像" :label-width="defaultLabelWidth">
          <el-upload
            :action="''"
            :before-upload="imgUpload"
            :show-file-list="false"
            class="avatar-uploader"
            accept=".jpg, .jpeg, .png, .gif"
          >
            <img
              v-if="editorform.headImgUrl"
              :src="baseImgurl + editorform.headImgUrl"
              class="head"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item
          label="昵称"
          :label-width="defaultLabelWidth"
          maxlength="20"
        >
          <el-input
            v-model="editorform.nickName"
            autocomplete="off"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="手机号码"
          :label-width="defaultLabelWidth"
          prop="mobile"
          maxlength="20"
        >
          <el-input
            v-model="editorform.mobile"
            autocomplete="off"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          :label-width="defaultLabelWidth"
          prop="email"
          maxlength="50"
        >
          <el-input
            v-model="editorform.email"
            autocomplete="off"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="身份证号"
          :label-width="defaultLabelWidth"
          prop="idCard"
          maxlength="20"
        >
          <el-input
            v-model="editorform.idCard"
            autocomplete="off"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="居住地"
          :label-width="defaultLabelWidth"
          maxlength="50"
        >
          <el-input
            v-model="editorform.location"
            autocomplete="off"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle('editorform')">取 消</el-button>
        <el-button type="primary" @click="confirmEditor">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="个人信息修改" :visible.sync="libraryFormShow">
      <el-form
        :model="library"
        :rules="rules"
        ref="libraryForm"
        label-position="left"
      >
        <el-form-item
          label="开馆时间"
          :label-width="defaultLabelWidth"
          prop="beginTime"
          maxlength="20"
        >
          <el-time-select
            v-model="library.beginTime"
            format="HH:mm:ss"
            :picker-options="{
              start: '07:30:00',
              step: '00:15:00',
              end: '12:30:00',
            }"
            placeholder="选择时间"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item
          label="闭馆时间"
          :label-width="defaultLabelWidth"
          prop="endTime"
          maxlength="20"
        >
          <el-time-select
            v-model="library.endTime"
            format="HH:mm:ss"
            :picker-options="{
              start: '18:30:00',
              step: '00:15:00',
              end: '23:30:00',
            }"
            placeholder="选择时间"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item
          label="图书租金"
          :label-width="defaultLabelWidth"
          prop="email"
          maxlength="50"
        >
          <el-input
            v-model="library.perDayPay"
            autocomplete="off"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle('libraryForm')">取 消</el-button>
        <el-button type="primary" @click="libraryChange()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    let baseImgurl = window.location.origin;
    let defaultHeadImg = baseImgurl + "/public/default_user.jpeg";
    return {
      baseImgurl,
      defaultHeadImg,
      libraryFormShow: false,
      passwordFormShow: false,
      editorformShow: false,
      defaultLabelWidth: "6vw",
      user: {
        role: "employee",
      },
      library: {
        beginTime: "",
        endTime: "",
        perDayPay: "",
      },
      editorform: {
        id: "",
        nickName: "",
        headImgUrl: "",
        location: "",
        idCard: "",
        mobile: "",
        email: "",
      },
      passwordForm: {
        oldPassword: "",
        newPassword: "",
      },
      rules: {
        beginTime: [
          {
            required: true,
            message: "开馆时间不能为空！",
            trigger: "blur",
          },
        ],
        endTime: [
          {
            required: true,
            message: "闭馆时间不能为空！",
            trigger: "blur",
          },
        ],
        perDayPay: [
          {
            required: true,
            message: "老密码不能为空！",
            trigger: "blur",
          },
          { type: "number", message: "必须为数字值！" },
        ],
        oldPassword: [
          {
            required: true,
            message: "老密码不能为空！",
            trigger: "blur",
          },
          {
            min: 5,
            max: 15,
            message: "长度在 5 到 15 个字符",
            trigger: "blur",
          },
        ],
        newPassword: [
          {
            required: true,
            message: "新密码不能为空！",
            trigger: "blur",
          },
          {
            min: 5,
            max: 15,
            message: "长度在 5 到 15 个字符",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "手机号码不能为空！",
            trigger: "blur",
          },
          { validator: this.$validator.mobile, trigger: "blur" },
        ],
        idCard: [
          {
            required: true,
            message: "身份证号不能为空！",
            trigger: "blur",
          },
          { validator: this.$validator.idCard, trigger: "blur" },
        ],
        email: [{ validator: this.$validator.email, trigger: "blur" }],
      },
    };
  },
  methods: {
    getUserInfo() {
      let that = this;
      this.$axios.get("/api/v1/user/info").then((data) => {
        that.user = data;
      });
    },
    getLibraryConfig() {
      let that = this;
      this.$axios.get("/api/v1/library/config").then((data) => {
        that.library = data;
      });
    },
    imgUpload(file) {
      let message = this.$message;
      const isIMAGE = file.type === "image/jpeg" || "image/gif" || "image/png";
      const isLt800K = file.size / 1024 < 1024;

      if (!isIMAGE) {
        message.error("上传文件只能是图片格式!");
        return false;
      }
      if (!isLt800K) {
        message.error("上传文件大小不能超过 1M!");
        return false;
      }
      if (isIMAGE && isLt800K) {
        var formdata = new FormData();
        formdata.append("file", file);
        let that = this;
        this.$axios
          .post("/api/v1/upload", formdata)
          .then((res) => {
            that.editorform.headImgUrl = res.url;
          })
          .catch((e) => {
            message.error(e.data.message);
          });
      }
      return false;
    },
    handleEditor() {
      this.editorform = this.user;
      this.editorformShow = true;
    },
    cancle(formName) {
      this.$refs[formName].resetFields();
      if (formName == "editorform") {
        this.getUserInfo();
      }
      this.libraryFormShow = false;
      this.passwordFormShow = false;
      this.editorformShow = false;
    },
    libraryChange() {
      let that = this;
      this.$refs["libraryForm"].validate((valid) => {
        if (valid) {
          this.$axios.put("/api/v1/library", this.library).then((data) => {
            if (data.result) {
              that.$message.success({
                message: "修改成功",
                center: true,
                offset: screen.availHeight * 0.32,
                duration: 1200,
              });
              that.$refs["libraryForm"].resetFields();
              that.libraryFormShow = false;
            }
          });
        }
      });
    },
    confirmChange() {
      let that = this;
      this.$refs["passwordForm"].validate((valid) => {
        if (valid) {
          this.$axios
            .put("/api/v1/user/change_password", this.passwordForm)
            .then((data) => {
              if (data.result) {
                that.$message.success({
                  message: "修改成功",
                  center: true,
                  offset: screen.availHeight * 0.32,
                  duration: 1200,
                });
                that.$refs["passwordForm"].resetFields();
                that.passwordFormShow = false;
              }
            })
            .catch((err) => {
              that.$message.error({
                message: err.data.message,
                center: true,
                offset: screen.availHeight * 0.32,
                duration: 1200,
              });
            });
        }
      });
    },
    confirmEditor() {
      let that = this;
      this.$refs["editorform"].validate((valid) => {
        if (valid) {
          this.$axios
            .put("/api/v1/user", this.editorform)
            .then((data) => {
              if (data.result) {
                that.$message.success({
                  message: "修改成功",
                  center: true,
                  offset: screen.availHeight * 0.32,
                  duration: 1200,
                });
                that.$refs["editorform"].resetFields();
                that.getUserInfo();
                that.editorformShow = false;
              }
            })
            .catch((err) => {
              that.$message.error({
                message: err.data.message,
                center: true,
                offset: screen.availHeight * 0.32,
                duration: 1200,
              });
            });
        }
      });
    },
  },
  computed: {},
  mounted() {
    let that = this;
    this.$axios.post("/api/v1/user/verified").then((data) => {
      that.user = data;
    });

    this.getUserInfo();
    this.getLibraryConfig();
  },
};
</script>

<style>
.library {
  width: 100%;
  height: 10vw;
}

.description {
  margin-top: 1.25vw;
}
</style>
